﻿/****************************************************************************************************
	Copyright (C) 2010 RapidWebDev Organization (http://rapidwebdev.org)
	Author: Eunge, Legal Name: Jian Liu, Email: eunge.liu@RapidWebDev.org

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************************************/

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace BaoJianSoft.Common.Data
{
	/// <summary>
	/// DataContext Factory
	/// </summary>
	public static class DataContextFactory
	{
		private static object syncObject = new object();
		private static Dictionary<string, DataContextSetting> dataContextSettings;

		private static IDictionary<string, DataContextSetting> DataContextSettings
		{
			get
			{
				if (dataContextSettings == null)
				{
					lock (syncObject)
					{
						if (dataContextSettings == null)
						{
							dataContextSettings = new Dictionary<string, DataContextSetting>();
							DataContextConfiguration dataContextConfiguration = ConfigurationManager.GetSection("dataContext") as DataContextConfiguration;
							foreach (DataContextSetting setting in dataContextConfiguration.DataContextSettings)
							{
								if (!dataContextSettings.ContainsKey(setting.Name))
									dataContextSettings.Add(setting.Name, setting);
							}
						}
					}
				}

				return dataContextSettings;
			}
		}

		/// <summary>
		/// Create DataContext instance from Spring IoC by specified generic data context type.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <returns></returns>
		public static T Create<T>() where T : System.Data.Linq.DataContext
		{
			string dataContextName = typeof(T).Name;
			if (!DataContextSettings.ContainsKey(dataContextName)) return null;

			DataContextSetting setting = DataContextSettings[dataContextName];
			Type dataContextType = Kit.GetType(setting.Type);

			T dataContext = Activator.CreateInstance(dataContextType, ConfigurationManager.ConnectionStrings[setting.ConnectionString].ConnectionString) as T;
			dataContext.Log = Console.Out;
			return dataContext;
		}
	}
}

